<template>
  <div id="content">
      <div id="map" ref="map"></div>
      <h1 id="msg"></h1>
  </div>
</template>

<script>
import "ol/ol.css";
import { Map, View,Feature } from "ol";
import Tile from "ol/layer/Tile";
import { fromLonLat } from "ol/proj";
import { XYZ,Vector as VectorSource } from "ol/source";
import { Vector as VectorLayer } from "ol/layer";
import { Polygon,LineString,Point } from "ol/geom";
import { Style,Circle,Stroke,Fill } from "ol/style";
import { Select,Draw } from "ol/interaction";
import { createBox } from "ol/interaction/Draw";
import { never } from "ol/events/condition";


export default {
  name: "AppRectangleSelect",
  data() {
      return {
      };
  },
  methods: {
      /**
       * 初始化一个 openlayers 地图
       */
      initMap() {
          let target = "map"; //跟页面元素的 id 绑定来进行渲染
          let tileLayer = [
              new Tile({
                  source: new XYZ({
                    url: "https://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}",
                  })
              })
          ];
          let view = new View({
              center: fromLonLat([104.912777, 34.730746]), //地图中心坐标
              zoom: 4.5 //缩放级别
          });
          this.map = new Map({
              target: target, //绑定dom元素进行渲染
              layers: tileLayer, //配置地图数据源
              view: view //配置地图显示的options配置（坐标系，中心点，缩放级别等）
          });
      }
  },
  mounted() {
    // 创建要素图层
    var vectorLayer = new  VectorLayer({
            source: new VectorSource({
                features: [
                    new Feature({
                        geometry: new Polygon([[
                            [119.0, 29.0],
                            [119.2, 29.0],
                            [119.2, 29.2],
                            [119.0, 29.2],
                            [119.0, 29.0]
                        ]]),
                        name: 'A'
                    }),
                    new  Feature({
                        geometry: new Polygon([[
                            [119.4, 29.0],
                            [119.6, 29.0],
                            [119.5, 29.2],
                            [119.4, 29.0]
                        ]]),
                        name: 'B'
                    }),
                    new  Feature({
                        geometry: new LineString([
                            [119.0, 29.4],
                            [119.2, 29.3],
                            [119.4, 29.5],
                            [119.6, 29.3],
                            [119.8, 29.6]
                        ]),
                        name: 'C'
                    }),
                    new  Feature({
                        geometry: new  Point([119.4, 29.6]),
                        name: 'D'
                    }),
                ]
            }),
            style: new  Style({
                image: new Circle({
                    radius: 30,
                    stroke: new Stroke({
                        width: 4,
                        color: 'blue'
                    }),
                    fill: new  Fill({
                        color: 'yellow'
                    })
                }),
                stroke: new  Stroke({
                    width: 4,
                    color: 'blue'
                }),
                fill: new  Fill({
                    color: 'yellow'
                })
            })
        });

       // 创建绘制图层
       var drawLayer = new  VectorLayer({
            source: new  VectorSource(),
            style: new  Style()
        });
      // let tileLayer =  new Tile({
      //     source: new XYZ({
      //       url: "https://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}",
      //     })
      // });

      // this.initMap();
       // 创建地图
       var map = new  Map({
            target: 'map',
            layers: [
              // tileLayer,
              vectorLayer,
              drawLayer
            ],
            view: new  View({
                projection: 'EPSG:4326',
                center: [119.2, 29.2],
                zoom: 10
            })
        });

       // 创建选择工具，用于盛放矩形框内的要素
       var select = new Select({
            condition: never,
            style: new  Style({
                image: new  Circle({
                    radius: 30,
                    stroke: new  Stroke({
                        width: 4,
                        color: 'red'
                    }),
                    fill: new  Fill({
                        color: 'green'
                    })
                }),
                stroke: new  Stroke({
                    width: 4,
                    color: 'red'
                }),
                fill: new  Fill({
                    color: 'green'
                })
            })
        });

        // 创建绘制矩形工具
        var drawBox = new  Draw({
            source: drawLayer.getSource(),
            type: 'Circle',
            geometryFunction:  createBox()
        });

        // 开始绘制，清除已有要素
        drawBox.on('drawstart', function () {
            select.getFeatures().clear();
            drawLayer.getSource().clear();
        });

        // 结束绘制
        drawBox.on('drawend', function (e) {
            if (e.feature) {
                // 获取框选范围
                var geometry = e.feature.getGeometry();
                var extent = geometry.getExtent();

                // 查询框选范围内的所有点
                vectorLayer.getSource().forEachFeatureIntersectingExtent(extent, function (feature) {
                    select.getFeatures().push(feature);
                });

                // 遍历被选中的要素
                var selected = [];
                var selectedFeatures = select.getFeatures();
                for (var i = 0; i < selectedFeatures.getLength(); i++) {
                    var feature = selectedFeatures.item(i);
                    var name = feature.get('name');
                    selected.push(name);
                }

                // 输出查询结果
                var msg = selected.join('、');
                document.getElementById('msg').innerText = '被选中的要素：' + msg;
            }
        });

        // 添加交互工具
        map.addInteraction(drawBox);
        map.addInteraction(select);
  }
};
</script>

<style lang="scss" scoped>
#map {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}
/*移除OSM的链接*/
:deep(.ol-attribution){ 
  display: none;
}
</style>
